package com.zero.service.impl;

import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.zero.mapper.UsersMapper;
import com.zero.pojo.Users;
import com.zero.service.UserService;
import com.zero.utils.MD5Utils;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private Sid sid;

	@Autowired
	private UsersMapper userMapper;

	@Override
	public boolean queryUserName(String userName) {
		Users user = new Users();
		user.setUsername(userName);
		Users result = userMapper.selectOne(user);
		return result == null ? false : true;
	}

	/**
	 * 查询用户是否存在
	 * 
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.SUPPORTS)
	@Override
	public Users queryLoginUser(Users user) throws Exception {
		Example userExample = new Example(Users.class);
		Criteria criteria = userExample.createCriteria();
		criteria.andEqualTo("username", user.getUsername());
		criteria.andEqualTo("password", MD5Utils.getMD5Str(user.getPassword()));
		Users result = userMapper.selectOneByExample(userExample);
		return result;
	}

	@Override
	public Users savaUser(Users user) throws Exception {
		// 为每个用户生成唯一的二维码
		user.setQrcode("");

		user.setId(sid.nextShort());
		user.setNickname(user.getUsername());
		user.setFaceImage("");
		user.setFaceImageBig("");
		user.setPassword(MD5Utils.getMD5Str(user.getPassword()));
		userMapper.insert(user);
		return user;

	}

}
